var Page = {
    calendarData: [],      // 所有价格日历数据
    abandonData: [],       // 删除价格日历的日期
    selectDate: [],        // 价格日历中选择的日期
    priceLabels: [],       // 所有价格分类
    priceLabel: null,      // 默认价格分类 id
    currentPriceLabel: {}, // 当前编辑的价格分类
    calendar: null,
    isEdited: false,       // 价格日历修改了但没有保存
    init: function () {
        Page.embedCalendar();
        Page.modalPriceEvents();
        Page.flightEvents();
        Page.hotelEvents();
        Page.priceLabelEvents();
        Page.priceTypeEvents();
        Page.formEvents();
    },
    embedCalendar: function () {
        Page.calendar = $('#calendar').fullCalendar({
            editable: false,
            selectable: true,
            unselectAuto: false,
            selectHelper: true,
            titleFormat: 'YYYY-MM',
            dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
            select: function (start, end, jsEvent, view) {
                Page.daySelectEvents(start, end, jsEvent, view);
            }
        });
        $('#price-edit').on('click', Page.showPricePopup);
        $('#price-save').on('click', Page.saveCalendarData);
        Page.getPriceDataFromRemote();
    },
    daySelectEvents: function (start, end, jsEvent, view) {
        console.log('start: ', start);
        console.log('end: ', end);
        console.log('daySelectEvents: ', view);
        var start = moment(start),
            end = moment(end),
            hours = end.diff(start, 'hours'),
            highlightDate = function (date) {
                Page.selectDate.push(date.format('YYYY-MM-DD'));
                $('.fc-highlight').removeClass('fc-highlight');
                $('td[data-date='+date.format('YYYY-MM-DD')+']').addClass('fc-select-highlight');
            },
            pushDate = function (date, jsEvent) {
                if ( jsEvent.metaKey || jsEvent.ctrlKey ) { // Command 多选
                    highlightDate(date);
                }else if ( jsEvent.shiftKey ){ // Shift 连选
                    // alert('哎哟，你按住了 shift')
                    highlightDate(date);
                }else{ // 单选
                    Page.selectDate = [];
                    $('.fc-select-highlight').removeClass('fc-select-highlight');
                    highlightDate(date);
                }
            },
            pushDates = function (start, end, jsEvent) {
                var start = start.format('YYYY-MM-DD'),
                    end = end.subtract(1, 'days').format('YYYY-MM-DD'); // fullcalendar end day fix
                console.log('start', start);
                console.log('end', end);
                if ( jsEvent.metaKey || jsEvent.ctrlKey ) { // Command 多选
                    while ( start <= end ){
                        highlightDate(moment(start));
                        start = moment(start).add(1, 'd').format('YYYY-MM-DD');
                    }
                }else if ( jsEvent.shiftKey ){ // Shift 连选
                    // alert('按下 shift')
                    while ( start <= end ){
                        highlightDate(moment(start));
                        start = moment(start).add(1, 'd').format('YYYY-MM-DD');
                    }
                }else{
                    Page.selectDate = [];
                    $('.fc-select-highlight').removeClass('fc-select-highlight');
                    while ( start <= end ){
                        highlightDate(moment(start));
                        start = moment(start).add(1, 'd').format('YYYY-MM-DD');
                    }
                }
            };
        if ( hours == 24 ) { // one day
            pushDate(start, jsEvent);
        } else{
            pushDates(start, end, jsEvent);
        }

        $('#price-edit').removeClass('disabled');
        console.log('Page.selectDate',Page.selectDate);
    },
    renderPriceLabel: function () {
        var html = '';
        $.each(Page.priceLabels, function(i, val) {
            html += '<div class="control-group"><label class="control-label" for="price-name-'+ val.pk +'">'+ val.name +'</label><div class="controls"><input class="price-label" min="0" data-id="'+ val.pk +'" type="number" id="price-name-'+ val.pk +'" placeholder="输入价格"></div></div>';
        });
        $('#price-label-input').html(html);
    },
    renderPricePopup: function () {
        var render_data = {};
        $.each(Page.selectDate, function(i, val) {
            var content = '<span class="badge">'+ val +'</span>';
            $(content).appendTo('#newCalendarDate p');
        });
        $.each(Page.selectDate, function(i, val) {
            var data = $.grep(Page.calendarData, function (data) {
                return data.date == val;
            })[0];
            if ( data ) { // 选择的日期是否有价格日历
                if ( i == 0 ) { // 第一个日期
                    render_data.stock = data.stock;
                    render_data.label_prices = data.label_prices ? data.label_prices : data.price;
                } else{
                    // 判断之后的日期价格日历是否与第一天一致
                    if ( data.stock !== render_data.stock && data.label_prices !== render_data.label_prices ) {
                        render_data = null;
                        return false;
                    }
                }
            }else{
                render_data = null;
                return false;
            }
        });
        $('#manageCalendarPrice').find('form')[0].reset();

        console.log('render_data: ', render_data);
        if ( render_data ) {
            $('#stock').val(render_data.stock);
            $.each(render_data.label_prices, function(id, val) {
                $('#price-name-'+id).val(val.price)
            });
        }
    },
    showPricePopup: function (e) {
        e.preventDefault();
        if ( Page.priceLabels.length === 0 ) {
            alert('请先添加价格分类')
            return false;
        }
        if ( $(this).hasClass('disabled') ) {
            alert('请先选择日期');
            return;
        }
        $("#manageCalendarPrice").modal();
        Page.renderPricePopup();
    },
    saveCalendarData: function (e) {
        e.preventDefault();
        if ( Page.calendarData.length === 0 ) {
            alert('价格日历不能为空');
            return false;
        }
        Page.isEdited = false;
        var data = JSON.stringify(Page.calendarData);
        $.ajax({
            url: URL_SUB_PRODUCT_PRICES,
            type: 'POST',
            dataType: 'json',
            data: {
                'data': JSON.stringify(Page.abandonData),
                'action': 'remove',
                'pk': PRODUCT_PK,
                'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (data) {
                if(!data.success){
                    alert('移除被删除价格日历失败!');
                    Page.isEdited = true;
                }else{
                    Page.abandonData = [];
                }
            }
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            alert('移除被删除价格日历失败! 服务器问题');
        })
        .always(function() {
            console.log("complete");
        });

        $.ajax({
            url: URL_SUB_PRODUCT_PRICES,
            type: 'POST',
            dataType: 'json',
            data: {
                'data': data,
                'pk': PRODUCT_PK || 0,
                'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (data) {
                if(!data.success){
                    alert('保存失败!');
                    Page.isEdited = true;
                }else{
                    alert('保存价格日历成功')
                }
            }
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            alert('保存价格日历成功 服务器问题');
        })
        .always(function() {
            console.log("complete");
        });
    },
    getPriceDataFromRemote: function () {
        /*
        [{
            date: '2015-05-05',
            stock: 5,
            price: 100,
            label_prices: {
                id: {
                    'name': '成人价',
                    'price': 100
                }
            }
        }]
        */
        var url = URL_SUB_PRODUCT_PRICES + '?pk=' + PRODUCT_PK;
        // get sub product price
        $.get(url, function(result){
            console.log('getPriceData: ', result);
            if (result.data.length > 0) {
                Page.renderCalendar(result.data);
            }else{
                Page.isEdited = true;
            }
        }, 'json');
    },
    renderCalendar: function (data) {
        if (data) {
            Page.calendarData = data;
        }else{
            Page.isEdited = true;
        }
        $.each(Page.calendarData, function(i, val) {
            var date = val.date,
                stock = val.stock || 0,
                price = val.price, // fullcalendar 展示用的默认价格
                title = '￥'+ price + ', 库存 ' + stock;
            val['id'] = 'price-date-' + date;
            val['title'] = title;
        });
        console.log('Page.calendarData: ', Page.calendarData);
        Page.calendar.fullCalendar('removeEventSource', Page.calendarData);
        Page.calendar.fullCalendar('addEventSource', Page.calendarData);
        if ( Page.calendarData.length === 0 ) {
            Page.isEdited = true;
        }
        // Page.calendar.fullCalendar('updateEvent', Page.calendarData);
    },
    updateCalendarData: function () {
        var input = $('#manageCalendarPrice').find('input'),
            label = $('#manageCalendarPrice').find('.price-label'),
            label_prices = {},
            default_price = null,
            stock = parseFloat($('#stock').val()),
            can_close_modal = true;
        input.each(function () {
            if ($.trim($(this).val()) == '') {
                alert('填完了吗');
                can_close_modal = false;
                return false;
            }
        })
        if ( String(stock).indexOf(".") > -1 ) {
            alert('请输入整数');
            can_close_modal = false;
            return false;
        }
        $.each(label, function(i, val) {
            // 获取价格信息
            // console.log('val: ',val);
            var id = val.getAttribute('data-id'),
                name = val.getAttribute('placeholder');
                price = parseFloat(val.value);
            label_prices[id] = {
                'name': name,
                'price': price
            }
            if ( id == Page.priceLabel ) {
                default_price = price;
            }
        });
        $.each(Page.selectDate, function(i, val) {
            // 把新价格写入 fullcalendar
            console.log(val);
            var data = {
                id: 'price-date-' + val,
                date: val,
                stock: stock,
                label_prices: label_prices,
                price: default_price
            }
            $.each(Page.calendarData, function(j, data) {
                // 把旧价格从 fullcalendar 去除
                if ( data.date == val ) {
                    Page.calendarData.splice(j, 1);
                    return false;
                }

            });
            Page.calendarData.push(data);
        });
        
        if ( can_close_modal ) {
            Page.renderCalendar();
            $('#manageCalendarPrice').modal('hide');
        }
        
    },
    clearDatePrice: function () {
        $.each(Page.selectDate, function(i, val) {
            var date = $.grep(Page.calendarData, function (data) {
                return data.date == val;
            })[0];
            if ( date ) {
                Page.abandonData.push({
                    date: val
                });
            }
            $.each(Page.calendarData, function(j, data) {
                if ( data.date == val ) {
                    Page.calendarData.splice(j, 1);
                    return false;
                }
            });
        });
        Page.renderCalendar();
        $('#manageCalendarPrice').modal('hide');
    },
    hidePriceModal: function() {
        $('#newCalendarDate p').html('');
        $('#newCalendarPrice, #newCalendarChildPrice, #newCalendarStock').val('');
    },
    modalPriceEvents: function () {
        $('#update').on('click', Page.updateCalendarData);
        $('#clear').on('click', Page.clearDatePrice);
        $('#manageCalendarPrice').on('hidden', Page.hidePriceModal);
    },
    addFlight: function (e) {
        e.preventDefault();
        $('#edit-hotel-flight-popup').modal('show');
        $('#edit-hotel-flight-popup').find('iframe').attr('src', URL_FLIGHT);
        $('#edit-hotel-flight-popup').find('h3').html('添加航班');
    },
    appendFlight: function (pk, title) {
        if($('#flight-' + pk)[0]){
            $('#flight-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_flights').val().split(',');
            ids.push(pk);
            $('#id_flights').val(ids.join(','));

            var html = '<li id="flight-' + pk + '" data-pk="' + pk +
                    '"><a class="name" href="###">' + title +
                    '</a><a class="close" href="###">&times;</a></li>';
            $('#flight-panel').append(html);
        }
        $('#edit-hotel-flight-popup').modal('hide');
    },
    editFlight: function () {
        var id = $(this).parent('li').attr('data-pk');
        var url = URL_FLIGHT + '?id=' + id;
        $('#edit-hotel-flight-popup').modal('show');
        $('#edit-hotel-flight-popup').find('iframe').attr('src', url);
        $('#edit-hotel-flight-popup').find('h3').html('编辑航班');
    },
    deleteFlight: function (e) {
        e.preventDefault();
        var pk = $(this).parent('li').data('pk');
        $('#flight-' + pk).remove();
        var content = $('#id_flights').val();
        $('#id_flights').val(content.replace(pk, ''));
    },
    flightEvents: function () {
        $('#add-flight').on('click', Page.addFlight);
        $('#flight-panel').on('click', '.name', Page.editFlight);
        $('#flight-panel').on('click', '.close', Page.deleteFlight);
        $('#flight-panel').sortable({
            stop: function(event, ui){
                var ids = [];
                $('#flight-panel').find('li').each(function(){
                    var e = $(this);
                    ids.push(e.data('pk'));
                })
                $('#id_flights').val(ids.join(','));
            }
        });
        $('#flight-panel').disableSelection();
    },
    addHotel: function (e) {
        e.preventDefault();
        $('#add-hotel-popup').modal('show');
        $('#add-hotel-popup').find('iframe').attr('src', URL_HOTEL);
    },
    appendHotel: function (pk, title){
        $('#add-hotel-popup').modal('hide');
        if($('#hotel-' + pk)[0]){
            $('#hotel-' + pk).find('a.name').text(title);
        } else {
            var ids = $('#id_hotels').val().split(',');
            ids.push(pk);
            $('#id_hotels').val(ids.join(','));

            var html = '<li id="hotel-' + pk + '" data-pk="' + pk +
                    '"><a class="name" href="###">' + title +
                    '</a><a class="close" href="###">&times;</a></li>';
            $('#hotel-panel').append(html);
        }
    },
    editHotel: function (e) {
        e.preventDefault();
        var id = $(this).parent('li').attr('data-pk');
        var url = URL_HOTEL + '?id=' + id;
        $('#edit-hotel-flight-popup').modal('show');
        $('#edit-hotel-flight-popup').find('iframe').attr('src', url);
        $('#edit-hotel-flight-popup').find('h3').html('编辑酒店');
    },
    deleteHotel: function (e) {
        e.preventDefault();
        var pk = $(this).parent('li').data('pk');
        $('#hotel-' + pk).remove();
        var content = $('#id_hotels').val();
        $('#id_hotels').val(content.replace(pk, ''));
    },
    chooseHotel: function (e) {
        e.preventDefault();
        var id = $('#all-hotels option:selected').val(),
            title = $('#all-hotels option:selected').attr('data-name');
        if ( id == '' ) {
            alert('请选择酒店');
            return false;
        } else{
            Page.appendHotel(id, title);
            $('#edit-hotel-flight-popup').modal('hide');
        };
    },
    hotelEvents: function () {
        $('#add-hotel').on('click', Page.addHotel);
        $('#choose-hotel').on('click', Page.chooseHotel);
        $('#hotel-panel').on('click', '.name', Page.editHotel);
        $('#hotel-panel').on('click', '.close', Page.deleteHotel);
        $('#all-hotels').select2({
            placeholder: '--请选择一个酒店--'
        });
    },
    addPriceLabel: function (e) {
        e.preventDefault();
        var url = $(this).attr('action'),
            name =  $('#add-price-label-popup .new-name').val(),
            isMain = $('#add-price-label-popup .is-main-checkbox')[0].checked ? true : false,
            data = $(this).serialize();
        $('#add-price-label-popup .btn-success').addClass('disabled');
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (data) {
                if ( data > 0 ) {
                    $('#add-price-label-popup').modal('hide').find('.new-name').val('');
                    Page.appendPriceLabel(data, name, isMain);
                }else{
                    alert('出错啦');
                }
                $('#add-price-label-popup .btn-success').removeClass('disabled');
                console.log(data);
            }
        });
    },
    editPriceLabel: function (e) {
        e.preventDefault();
        var pk = Page.currentPriceLabel.pk,
            subProductId = $('#sub-product-pk').val(),
            name = $('#edit-price-label-popup .new-name').val(),
            data = $('#edit-price-label-popup form').serialize(),
            isMain = $('#edit-price-label-popup .is-main-checkbox')[0].checked ? true : false,
            url = '/dashboard/tp/sub_product_price_label/' + subProductId + '/rename/' + pk + '/';
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (data) {
                if (data) {
                    Page.appendPriceLabel(pk, name, isMain);
                    $('#edit-price-label-popup').modal('hide');
                }
            }
        });
        
    },
    delPriceLabel: function (e) {
        e.preventDefault();
        var labelId = Page.currentPriceLabel.pk,
            subProductId = $('#sub-product-pk').val(),
            confirm = window.confirm('删除价格分类会删掉价格日历中所有该分类的价格，真要这么做？');
            url = '/dashboard/tp/sub_product_price_label/'+subProductId+'/delete/'+ labelId +'/';
        if ( !confirm ) { return false; }
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: {},
            success: function (data) {
                if (data) {
                    Page.appendPriceLabel(labelId, null, false, true);
                    $('#edit-price-label-popup').modal('hide');
                }
            }
        });
    },
    appendPriceLabel: function (pk, name, is_main, delete_label) {
        if ( delete_label ) { // 删除价格分类
            $('#price-label-' + pk).hide();
            $.each(Page.priceLabels, function(i, label) {
                // 把价格分类从 Page.priceLabels 去除
                if ( label.pk == pk ) {
                    Page.priceLabels.splice(i, 1);
                    return false;
                }
            });
            Page.renderPriceLabel();
            return false;
        }
        if($('#price-label-' + pk)[0]){ // 修改价格分类
            $('#price-label-' + pk).find('b').text(name);
            $.each(Page.priceLabels, function(i, val) {
                if ( val.pk == pk ) {
                    Page.priceLabels.splice(i, 1);
                    return false;
                }
            });
        } else {
            var html = '<a data-pk="'
                     + pk + '" class="badge" id="price-label-'
                     + pk + '" href="###"><b>'
                     + name + '</b> <i class="icon-edit icon-white"></i></a>';

            $('#price-label-panel').append(html);
        }
        if ( is_main ) { // 添加默认价格样式
            Page.priceLabel = pk;
            $('#price-label-' + pk).addClass('badge-info').siblings().removeClass('badge-info');
            $.each(Page.priceLabels, function(i, label) {
                label.is_main = false;
            });
        }
        var data = {'pk': pk, 'name': name, 'is_main': is_main};
        Page.priceLabels.push(data);
        Page.renderPriceLabel();
    },
    showAddPriceLabelPopup: function (e) {
        e.preventDefault();
        var popup = $('#add-price-label-popup'),
            first = Page.priceLabels.length == 0;
        popup.modal('show');
        $('#add-new-name')[0].focus();
        if ( first ) {
            popup.find('.is-main-checkbox').attr({
                checked: true,
                disabled: true
            });
            popup.find('.is-main-value').attr({
                value: 'on'
            });
        }else{
            popup.find('.is-main-checkbox').attr({
                checked: false,
                disabled: false
            });
            popup.find('.is-main-value').attr({
                value: 'off'
            });
        }
    },
    showEidtPriceLabelPopup: function (e) {
        e.preventDefault();
        var popup = $('#edit-price-label-popup'),
            pk = $(this).attr('data-pk');
        Page.currentPriceLabel = $.grep(Page.priceLabels, function (label) {
                return label.pk == pk;
            })[0];
        var name = Page.currentPriceLabel.name,
            is_main = Page.currentPriceLabel.is_main;
        popup.modal('show').find('.new-name').val(name);
        if ( is_main ) {
            popup.find('.is-main-checkbox').attr({
                checked: true,
                disabled: true
            });
            popup.find('.is-main-value').attr({
                value: 'on'
            });
            // 默认价格不能删除
            $('#del-price-label').attr({
                disabled: true
            });
        }else{
            popup.find('.is-main-checkbox').attr({
                checked: false,
                disabled: false
            });
            popup.find('.is-main-value').attr({
                value: 'off'
            });
            $('#del-price-label').attr({
                disabled: false
            });
        }
    },
    checkboxTrigger: function () {
        var self = $(this),
            checked = self[0].checked == 1;
        if ( checked ) {
            self.parent('label').prev('input').val('on')
        } else{
            self.parent('label').prev('input').val('off')
        }
    },
    priceLabelEvents: function () {
        $('#add-price-label-popup form').on('submit', Page.addPriceLabel);
        $('#edit-price-label').on('click', Page.editPriceLabel)
        $('#add-price-label').on('click', Page.showAddPriceLabelPopup)
        $('#del-price-label').on('click', Page.delPriceLabel)
        $('#price-label-panel').on('click', 'a', Page.showEidtPriceLabelPopup)
        $('.is-main-checkbox').on('change', Page.checkboxTrigger)
    },
    changeProductStock: function () {
        $.each(Page.calendarData, function(i, val) {
            val.stock = 1;
        });

        Page.renderCalendar();
    },
    priceTypeEvents: function () {
    // City Hunter 定价方式

        var $inputs =  $('input[name=price_type]'),
            $controls = $inputs.parents('.controls');
        $inputs.on('change', function(e) {
            e.preventDefault();
            var type = $(this).val();
            if (type === 'bout') {
                var confirm = window.confirm('您更改了定价方式，库存默认调整为 1');
                if (confirm) {
                    // 选择「按每次」时，把产品库存改为1
                    Page.changeProductStock();
                }else{
                    $(':radio[value=people]').prop('checked', true);
                }
            }
        });
    },
    formEvents: function () {
        $('#sub-form').on('submit', function (e) {
            if ( Page.isEdited ) {
                e.preventDefault();
                alert('请先添加或保存价格日历')
            }
        })
    },
};

$(document).ready(function() {
    Page.init();
});